<template>
  <div class="login_container">
    <!-- <h1>这是Login组件</h1> -->
    <div class="login_box">
      <h3>登录</h3>
      <el-form
        :model="loginRuleForm"
        :rules="loginRules"
        ref="loginRef"
        label-width="100px"
      >
        <el-form-item label="账号：" prop="name">
          <el-input v-model="loginRuleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="pwd">
          <el-input v-model="loginRuleForm.pwd" type="password"></el-input>
        </el-form-item>
        <el-form-item class="login_btn">
          <el-button type="primary" @click="loginPre">登录</el-button>
          <el-button @click="resetLogin">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginRuleForm: {},
      loginRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 重置表单域方法
    resetLogin() {
      this.$refs.loginRef.resetFields();
    },
    // 表单校验
    loginPre() {
      this.$refs.loginRef.validate(async valid => {
        if (!valid) return;
        // 预校验通过
        const { data: res } = await this.$http.post(
          '/loginInfo',
          this.loginRuleForm
        );
        console.log(res);
        //判断请求是否成功
        if (res.code != 200) return this.$message.error('登录失败！');
        // 1.数据请求成功
        // 1.1 登录成功提示
        this.$message.success('您已成功登录!');
        // 1.2 将获取的token保存在sessionStorage中
        sessionStorage.setItem('token', res.user.token);
        //  1.3 编程式导航，跳转至 '/welcome'
        this.$router.push('/welcome');
      });
    }
  }
};
</script>
<style lang="less" scoped>
.login_container {
  height: 100%;
  background-color: #666;
  .login_box {
    width: 500px;
    height: 250px;
    background-color: #fff;
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 20px;
    > h3 {
      text-align: left;
      font-size: 16px;
      font-weight: 400;
    }
  }
}
</style>
